//
//  CTCContractEditVC.m
//  CTC
//
//  Created by 小龙 on 2017/4/18.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "CTCContractEditVC.h"
//#import "CTCConsultorDetailModel.h"
#import "CTCContractFileListVC.h"

@interface CTCContractEditVC ()<UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UILabel *fileNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *uploadResultLabel;
@property (weak, nonatomic) IBOutlet BWHTextView *contentTextView;
@property (weak, nonatomic) IBOutlet UIView *consultBackView;
@property (weak, nonatomic) IBOutlet UILabel *consultNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *consultPosiationLabel;
@property (weak, nonatomic) IBOutlet UILabel *consultCompanyLabel;
@property (weak, nonatomic) IBOutlet UIImageView *consultHeadImageView;
@property (weak, nonatomic) IBOutlet UIView *backView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *consultBtnHeightLayout;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *consultBtnTopLayout;
@property (weak, nonatomic) IBOutlet UIButton *upLoadBtn;
/*选择的咨询师id*/
@property (atomic, copy) NSString *cuserIdSelected;

/*真实文件名*/
@property (atomic, copy) NSString *realFileName;

/** 上传文件的路径 */
@property (nonatomic, copy) NSString *docFilePath;

@end

@implementation CTCContractEditVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setupNavBar];
    
    [self setupUI];
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadUI:) name:kGetChooseConsultModelNotification object:nil];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setupNavBar
{
    self.title = @"审合同";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemClick)];
    
}

- (void)setupUI
{

}


- (void)reloadUI:(NSNotification *)notification
{
    self.consultBackView.hidden = NO;
    
}



- (void)rightBarButtonItemClick
{


}

- (IBAction)chooseFileBtnClick {
    
    CTCContractFileListVC *vc = [[CTCContractFileListVC alloc]init];
    CTCNavigationController *nav = [[CTCNavigationController alloc]initWithRootViewController:vc];
    
    MPWeakSelf(self);
    vc.selecteFileReturnBlock = ^(NSString *docFilePath){
        NSArray *array = [docFilePath componentsSeparatedByString:@"/"];
        weakself.fileNameLabel.text = [array lastObject];
        weakself.docFilePath = docFilePath;
        weakself.upLoadBtn.enabled = YES;
        weakself.upLoadBtn.layer.borderColor = HEXCOLOR(0x2E8CE5).CGColor;
        [weakself.upLoadBtn setTitleColor:HEXCOLOR(0x2E8CE5) forState:UIControlStateNormal];
    };
    [self presentViewController:nav animated:YES completion:nil];
}



- (IBAction)uploadFileBtnClick {
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"file"] = [NSData dataWithContentsOfFile:self.docFilePath];
    [MBProgressHUD showAnimationHUD];
    
    [RequestTool postFile:kUploadUrl parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
//        UIImage *image =[UIImage imageNamed:@"moon"];
//        NSData *data = UIImagePNGRepresentation(image);
        
        
//        // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
//        // 要解决此问题，
//        // 可以在上传时使用当前的系统事件作为文件名
//        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//        // 设置时间格式
//        formatter.dateFormat = @"yyyyMMddHHmmss";
//        NSString *str = [formatter stringFromDate:[NSDate date]];
//        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        
        //上传
        /*
         此方法参数
         1. 要上传的[二进制数据]
         2. 对应网站上[upload.php中]处理文件的[字段"file"]
         3. 要保存在服务器上的[文件名]
         4. 上传文件的[mimeType]
         */
//        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];
         [formData appendPartWithFileURL:[NSURL fileURLWithPath:self.docFilePath] name:@"file" error:nil];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //上传进度
        // @property int64_t totalUnitCount;     需要下载文件的总大小
        // @property int64_t completedUnitCount; 当前已经下载的大小
        //
        // 给Progress添加监听 KVO
        NSLog(@"%f",1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        // 回到主队列刷新UI,用户自定义的进度条
        dispatch_async(dispatch_get_main_queue(), ^{
//            [MBProgressHUD].progress = 1.0 *
//            uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        DeLog(@"responseObject+++++:%@",responseObject);
        [MBProgressHUD  hideHUD];
        
        if ([responseObject[@"code"] integerValue] == 1) {
            self.uploadResultLabel.text = @"已上传完毕";
            self.realFileName = responseObject[@"data"];
            self.upLoadBtn.enabled = YES;
            self.upLoadBtn.layer.borderColor = HEXCOLOR(0xf9f9f9).CGColor;
            [self.upLoadBtn setTitleColor:HEXCOLOR(0xf9f9f9) forState:UIControlStateNormal];
        }
        //        CTCContractListModel *model = [CTCContractListModel yy_modelWithJSON:responseObject];
        //        if ([model.code integerValue] == 1) {
        //            [self.contractsArr addObjectsFromArray:model.contractArr];
        //            self.lastId += model.contractArr.count;
        //            [self.tableView reloadData];
        //        } else {
        //            [MBProgressHUD showErrorMessage:model.des];
        //            if ([model.code integerValue] == 2) {
        //                CTCLoginViewController *vc = [CTCLoginViewController viewControllerFromStoryboard];
        //                MPWeakSelf(self);
        //                vc.loginSuccess = ^(){
        //                    [weakself getNewContractsListData];
        //                };
        //                [self presentViewController:vc animated:YES completion:nil];
        //            }
        //        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"error+++++:%@",error);
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力，请检查网络"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }
    }];
    
    
}

- (IBAction)chooseConsultBtnClick {

//    CTCConsultorListViewController *vc = [[CTCConsultorListViewController alloc] initWithType:CTCConsultorListViewControllerTypeFromContract];
////    CTCNavigationController *nav = [[CTCNavigationController alloc]initWithRootViewController:vc];
////    [self presentViewController:nav animated:YES completion:nil];
//    [self.navigationController pushViewController:vc animated:YES];
}


-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

@end
